﻿using Microsoft.Extensions.Logging;
using RotovapPlatform.Application.Services.Devices;
using RotovapPlatform.Domain.Business.Interfaces;
using RotovapPlatform.Domain.Business.Machine.Enums;
using RotovapPlatform.Domain.Business.Recipes.Entities;
using RotovapPlatform.Domain.Common;
using RotovapPlatform.Domain.Services.Experiments;
using System;
using System.Threading.Tasks;
using static RotovapPlatform.Domain.Business.Machine.Enums.ExperimentConfigEnums;

namespace RotovapPlatform.Application.Services.Experiments
{
	/// <summary>
	/// 实验流程应用服务实现
	/// </summary>
	public class ExperimentProcessAppService : IExperimentProcessAppService, IDisposable
	{
		private readonly ILogger<ExperimentProcessAppService> _logger;
		private readonly IExperimentProcessDomainService _experimentProcessService;
		private readonly IDeviceAppService _deviceAppService;

		// 数据库访问接口
		private readonly IExperimentRepository _experimentRepository;
		private readonly IExperimentGroupRepository _experimentGroupRepository;

		/// <summary>
		/// 当前实验阶段变更事件
		/// </summary>
		public event EventHandler<ExperimentStageChangedEventArgs> ExperimentStageChanged;

		/// <summary>
		/// 当前实验子阶段变更事件
		/// </summary>
		public event EventHandler<ExperimentSubStageChangedEventArgs> ExperimentSubStageChanged;

		/// <summary>
		/// 获取当前实验ID
		/// </summary>
		public Guid? CurrentExperimentId => _experimentProcessService.CurrentExperimentId;

		/// <summary>
		/// 获取当前实验阶段
		/// </summary>
		public ExperimentStage? CurrentStage => _experimentProcessService.CurrentStage;

		/// <summary>
		/// 获取当前实验子阶段
		/// </summary>
		public ExperimentSubStage? CurrentSubStage => _experimentProcessService.CurrentSubStage;

		/// <summary>
		/// 构造函数
		/// </summary>
		public ExperimentProcessAppService(
			ILogger<ExperimentProcessAppService> logger,
			IExperimentProcessDomainService experimentProcessService,
			IDeviceAppService deviceAppService,
			IExperimentRepository experimentRepository,
			IExperimentGroupRepository experimentGroupRepository)
		{
			_logger = logger;
			_experimentProcessService = experimentProcessService;
			_deviceAppService = deviceAppService;
			_experimentRepository = experimentRepository;
			_experimentGroupRepository = experimentGroupRepository;

			// 订阅领域服务事件
			_experimentProcessService.ExperimentStageChanged += OnDomainExperimentStageChanged;
			_experimentProcessService.ExperimentSubStageChanged += OnDomainExperimentSubStageChanged;
		}

		/// <summary>
		/// 处理领域服务中的实验阶段变更事件
		/// </summary>
		private void OnDomainExperimentStageChanged(object sender, ExperimentStageChangedEventArgs e)
		{
			_logger.LogInformation($"应用服务: 转发实验 {e.ExperimentId} 阶段变更事件: {e.Stage}");
			ExperimentStageChanged?.Invoke(this, e);
		}

		/// <summary>
		/// 处理领域服务中的实验子阶段变更事件
		/// </summary>
		private void OnDomainExperimentSubStageChanged(object sender, ExperimentSubStageChangedEventArgs e)
		{
			_logger.LogInformation($"应用服务: 转发实验 {e.ExperimentId} 子阶段变更事件: {e.SubStage}");
			ExperimentSubStageChanged?.Invoke(this, e);
		}

		/// <summary>
		/// 执行物料&条件准备阶段
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteMaterialAndConditionPreparationAsync(Guid experimentId)
		{
			try
			{
				_logger.LogInformation($"应用服务: 开始执行实验 {experimentId} 的物料&条件准备阶段");

				// 1. 获取实验信息
				var experiment = await _experimentRepository.GetByIdAsync(experimentId);
				if (experiment == null)
				{
					_logger.LogWarning($"应用服务: 找不到实验 {experimentId}");
					return new OperationResult { Success = false, Message = $"找不到实验 {experimentId}" };
				}

				// 2. 更新实验状态
				experiment.Status = ExperimentStatus.Running;
				experiment.CurrentStage = ExperimentStage.MaterialAndConditionPreparation;
				experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
				await _experimentRepository.UpdateAsync(experiment);

				// 3. 调用领域服务执行物料&条件准备阶段
				var result = await _experimentProcessService.ExecuteMaterialAndConditionPreparationAsync(experiment);

				if (result.Success)
				{
					_logger.LogInformation($"应用服务: 实验 {experimentId} 的物料&条件准备阶段执行完成");
				}
				else
				{
					_logger.LogWarning($"应用服务: 实验 {experimentId} 的物料&条件准备阶段执行失败: {result.Message}");
				}

				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 执行实验 {experimentId} 的物料&条件准备阶段时发生错误");
				return new OperationResult { Success = false, Message = $"物料&条件准备阶段执行失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 执行旋蒸阶段
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteRotaryEvaporationAsync(Guid experimentId)
		{
			try
			{
				_logger.LogInformation($"应用服务: 开始执行实验 {experimentId} 的旋蒸阶段");

				// 1. 获取实验信息
				var experiment = await _experimentRepository.GetByIdAsync(experimentId);
				if (experiment == null)
				{
					_logger.LogWarning($"应用服务: 找不到实验 {experimentId}");
					return new OperationResult { Success = false, Message = $"找不到实验 {experimentId}" };
				}

				// 2. 更新实验状态
				experiment.CurrentStage = ExperimentStage.RotaryEvaporation;
				experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
				await _experimentRepository.UpdateAsync(experiment);

				// 3. 调用领域服务执行旋蒸阶段
				var result = await _experimentProcessService.ExecuteRotaryEvaporationAsync(experiment);

				if (result.Success)
				{
					_logger.LogInformation($"应用服务: 实验 {experimentId} 的旋蒸阶段执行完成");
				}
				else
				{
					_logger.LogWarning($"应用服务: 实验 {experimentId} 的旋蒸阶段执行失败: {result.Message}");
				}

				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 执行实验 {experimentId} 的旋蒸阶段时发生错误");
				return new OperationResult { Success = false, Message = $"旋蒸阶段执行失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 执行旋蒸残液处理阶段
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteEvaporationResidueProcessingAsync(Guid experimentId)
		{
			try
			{
				_logger.LogInformation($"应用服务: 开始执行实验 {experimentId} 的旋蒸残液处理阶段");

				// 1. 获取实验信息
				var experiment = await _experimentRepository.GetByIdAsync(experimentId);
				if (experiment == null)
				{
					_logger.LogWarning($"应用服务: 找不到实验 {experimentId}");
					return new OperationResult { Success = false, Message = $"找不到实验 {experimentId}" };
				}

				// 2. 更新实验状态
				experiment.CurrentStage = ExperimentStage.EvaporationResidueProcessing;
				experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
				await _experimentRepository.UpdateAsync(experiment);

				// 3. 调用领域服务执行旋蒸残液处理阶段
				var result = await _experimentProcessService.ExecuteEvaporationResidueProcessingAsync(experiment);

				if (result.Success)
				{
					_logger.LogInformation($"应用服务: 实验 {experimentId} 的旋蒸残液处理阶段执行完成");
				}
				else
				{
					_logger.LogWarning($"应用服务: 实验 {experimentId} 的旋蒸残液处理阶段执行失败: {result.Message}");
				}

				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 执行实验 {experimentId} 的旋蒸残液处理阶段时发生错误");
				return new OperationResult { Success = false, Message = $"旋蒸残液处理阶段执行失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 执行冷凝液处理阶段
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteCondensateProcessingAsync(Guid experimentId)
		{
			try
			{
				_logger.LogInformation($"应用服务: 开始执行实验 {experimentId} 的冷凝液处理阶段");

				// 1. 获取实验信息
				var experiment = await _experimentRepository.GetByIdAsync(experimentId);
				if (experiment == null)
				{
					_logger.LogWarning($"应用服务: 找不到实验 {experimentId}");
					return new OperationResult { Success = false, Message = $"找不到实验 {experimentId}" };
				}

				// 2. 更新实验状态
				experiment.CurrentStage = ExperimentStage.CondensateProcessing;
				experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
				await _experimentRepository.UpdateAsync(experiment);

				// 3. 调用领域服务执行冷凝液处理阶段
				var result = await _experimentProcessService.ExecuteCondensateProcessingAsync(experiment);

				if (result.Success)
				{
					_logger.LogInformation($"应用服务: 实验 {experimentId} 的冷凝液处理阶段执行完成");
				}
				else
				{
					_logger.LogWarning($"应用服务: 实验 {experimentId} 的冷凝液处理阶段执行失败: {result.Message}");
				}

				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 执行实验 {experimentId} 的冷凝液处理阶段时发生错误");
				return new OperationResult { Success = false, Message = $"冷凝液处理阶段执行失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 执行清洗阶段
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteCleaningAsync(Guid experimentId)
		{
			try
			{
				_logger.LogInformation($"应用服务: 开始执行实验 {experimentId} 的清洗阶段");

				// 1. 获取实验信息
				var experiment = await _experimentRepository.GetByIdAsync(experimentId);
				if (experiment == null)
				{
					_logger.LogWarning($"应用服务: 找不到实验 {experimentId}");
					return new OperationResult { Success = false, Message = $"找不到实验 {experimentId}" };
				}

				// 2. 更新实验状态
				experiment.CurrentStage = ExperimentStage.Cleaning;
				experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
				await _experimentRepository.UpdateAsync(experiment);

				// 3. 调用领域服务执行清洗阶段
				var result = await _experimentProcessService.ExecuteCleaningAsync(experiment);

				if (result.Success)
				{
					// 实验清洗阶段完成，更新整个实验状态为完成
					experiment.Status = ExperimentStatus.Completed;
					experiment.CurrentStage = ExperimentStage.Completed;
					experiment.ExecutionEndTime = DateTime.Now;
					await _experimentRepository.UpdateAsync(experiment);

					_logger.LogInformation($"应用服务: 实验 {experimentId} 的清洗阶段执行完成");
				}
				else
				{
					_logger.LogWarning($"应用服务: 实验 {experimentId} 的清洗阶段执行失败: {result.Message}");
				}

				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 执行实验 {experimentId} 的清洗阶段时发生错误");
				return new OperationResult { Success = false, Message = $"清洗阶段执行失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 执行整个实验
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <returns>实验对象</returns>
		public async Task<Experiment> ExecuteExperimentAsync(Guid experimentId)
		{
			try
			{
				_logger.LogInformation($"应用服务: 开始执行实验 {experimentId}");

				// 获取实验
				var experiment = await _experimentRepository.GetByIdAsync(experimentId);
				if (experiment == null)
				{
					_logger.LogWarning($"应用服务: 找不到实验 {experimentId}");
					return null;
				}

				// 更新实验状态为进行中
				experiment.Status = ExperimentStatus.Running;
				experiment.ExecutionStartTime = DateTime.Now;
				await _experimentRepository.UpdateAsync(experiment);

				// 如果当前阶段未设置，默认从第一个阶段开始
				if (experiment.CurrentStage == null)
				{
					experiment.CurrentStage = ExperimentStage.MaterialAndConditionPreparation;
					experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
				}

				experiment.CurrentStage = ExperimentStage.MaterialAndConditionPreparation;
				experiment.CurrentSubStage = ExperimentSubStage.NotStarted;

				// 基于当前阶段执行实验
				switch (experiment.CurrentStage)
				{
					case ExperimentStage.MaterialAndConditionPreparation:
						// 1. 物料&条件准备阶段
						var materialAndConditionResult = await ExecuteMaterialAndConditionPreparationAsync(experimentId);
						if (!materialAndConditionResult.Success)
						{
							await HandleExperimentFailureAsync(experiment, materialAndConditionResult.Message, "物料&条件准备阶段");
							return experiment;
						}
						goto case ExperimentStage.RotaryEvaporation;

					case ExperimentStage.RotaryEvaporation:
						// 2. 旋蒸阶段
						var evaporationResult = await ExecuteRotaryEvaporationAsync(experimentId);
						if (!evaporationResult.Success)
						{
							await HandleExperimentFailureAsync(experiment, evaporationResult.Message, "旋蒸阶段");
							return experiment;
						}
						goto case ExperimentStage.EvaporationResidueProcessing;

					case ExperimentStage.EvaporationResidueProcessing:
						// 3. 旋蒸残液处理阶段
						var residueResult = await ExecuteEvaporationResidueProcessingAsync(experimentId);
						if (!residueResult.Success)
						{
							await HandleExperimentFailureAsync(experiment, residueResult.Message, "旋蒸残液处理阶段");
							return experiment;
						}
						goto case ExperimentStage.CondensateProcessing;

					case ExperimentStage.CondensateProcessing:
						// 4. 冷凝液处理阶段
						var condensateResult = await ExecuteCondensateProcessingAsync(experimentId);
						if (!condensateResult.Success)
						{
							await HandleExperimentFailureAsync(experiment, condensateResult.Message, "冷凝液处理阶段");
							return experiment;
						}
						goto case ExperimentStage.Cleaning;

					case ExperimentStage.Cleaning:
						// 5. 清洗阶段
						var cleaningResult = await ExecuteCleaningAsync(experimentId);
						if (!cleaningResult.Success)
						{
							await HandleExperimentFailureAsync(experiment, cleaningResult.Message, "清洗阶段");
							return experiment;
						}
						break;

					default:
						_logger.LogWarning($"应用服务: 实验 {experimentId} 处于未知阶段 {experiment.CurrentStage}");
						await HandleExperimentFailureAsync(experiment, "未知的实验阶段", "未知阶段");
						return experiment;
				}

				// 实验完成，状态已在清洗阶段结束时更新
				_logger.LogInformation($"应用服务: 实验 {experimentId} 执行完成");
				return experiment;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 执行实验 {experimentId} 时发生未处理的错误");

				// 获取实验（可能之前已经获取过，但为了安全起见再次获取）
				var experiment = await _experimentRepository.GetByIdAsync(experimentId);
				if (experiment != null)
				{
					await HandleExperimentFailureAsync(experiment, ex.Message, "未知阶段");
				}

				throw;
			}
		}

		/// <summary>
		/// 处理实验失败
		/// </summary>
		private async Task HandleExperimentFailureAsync(Experiment experiment, string message, string stageName)
		{
			_logger.LogWarning($"应用服务: 实验 {experiment.ExperimentId} 在{stageName}失败: {message}");

			experiment.Status = ExperimentStatus.Failed;
			experiment.ErrorMessage = message;
			experiment.ExecutionEndTime = DateTime.Now;
			experiment.CurrentStage = ExperimentStage.Failed;

			await _experimentRepository.UpdateAsync(experiment);

			// TODO: 实现报警或通知逻辑
		}

		/// <summary>
		/// 获取实验状态
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <returns>实验状态</returns>
		public async Task<Experiment> GetExperimentStatusAsync(Guid experimentId)
		{
			try
			{
				_logger.LogInformation($"应用服务: 获取实验 {experimentId} 状态");
				return await _experimentRepository.GetByIdAsync(experimentId);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 获取实验 {experimentId} 状态时发生错误");
				throw;
			}
		}

		/// <summary>
		/// 获取实验组状态
		/// </summary>
		/// <param name="experimentGroupId">实验组ID</param>
		/// <returns>实验组状态</returns>
		public async Task<ExperimentGroup> GetExperimentGroupStatusAsync(Guid experimentGroupId)
		{
			try
			{
				_logger.LogInformation($"应用服务: 获取实验组 {experimentGroupId} 状态");
				return await _experimentGroupRepository.GetByIdAsync(experimentGroupId);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 获取实验组 {experimentGroupId} 状态时发生错误");
				throw;
			}
		}

		/// <summary>
		/// 获取实验参数
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <returns>实验参数</returns>
		public async Task<Experiment> GetExperimentParametersAsync(Guid experimentId)
		{
			try
			{
				_logger.LogInformation($"应用服务: 获取实验 {experimentId} 参数");
				return await _experimentRepository.GetByIdAsync(experimentId);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 获取实验 {experimentId} 参数时发生错误");
				throw;
			}
		}

		/// <summary>
		/// 获取设备状态
		/// </summary>
		/// <returns>设备状态</returns>
		public async Task<DeviceStatusInfo> GetDeviceStatusAsync()
		{
			try
			{
				_logger.LogInformation("应用服务: 获取设备状态");

				// TODO: 实现获取设备状态的具体逻辑
				// 这里返回一个临时的空对象，实际实现需要从设备服务获取真实状态
				return await Task.FromResult(new DeviceStatusInfo());
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 获取设备状态时发生错误");
				throw;
			}
		}

		/// <summary>
		/// 手动执行紧急停止
		/// </summary>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteEmergencyStopAsync()
		{
			try
			{
				_logger.LogInformation("应用服务: 开始执行紧急停止");

				// TODO: 实现紧急停止的具体逻辑
				// 主要步骤：
				// - 停止所有正在进行的动作
				// - 关闭加热、泵等危险设备
				// - 释放真空
				// - 更新实验状态为暂停或失败

				return new OperationResult { Success = true, Message = "紧急停止执行成功" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 执行紧急停止时发生错误");
				return new OperationResult { Success = false, Message = $"紧急停止执行失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 手动重置设备
		/// </summary>
		/// <returns>重置结果</returns>
		public async Task<OperationResult> ResetDeviceAsync()
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// 获取机械手状态
		/// </summary>
		/// <returns>机械手状态</returns>
		public async Task<RobotArmState> GetRobotArmStateAsync()
		{
			try
			{
				_logger.LogInformation("应用服务: 获取机械手状态");

				// TODO: 实现获取机械手实际状态的逻辑
				// 这里临时返回空闲状态，实际实现需要从设备服务获取真实状态
				return await Task.FromResult(RobotArmState.Idle);
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 获取机械手状态时发生错误");
				return RobotArmState.Error;
			}
		}

		/// <summary>
		/// 手动扫描物料条码
		/// </summary>
		/// <returns>操作结果，包含条码数据</returns>
		public async Task<OperationResult<string>> ManualScanMaterialBarcodeAsync()
		{
			try
			{
				_logger.LogInformation("应用服务: 开始手动扫描物料条码");

				// TODO: 实现手动扫描物料条码的具体逻辑
				// 主要步骤：
				// - 激活扫码器
				// - 等待扫码完成
				// - 返回扫码结果

				// 临时返回一个模拟的条码数据
				return await Task.FromResult(new OperationResult<string>
				{
					Success = true,
					Message = "扫码成功",
					Data = "SAMPLE-BAR-CODE-001"
				});
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 手动扫描物料条码时发生错误");
				return new OperationResult<string> { Success = false, Message = $"扫码失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 手动验证物料
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <param name="barcodeData">条码数据</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ManualValidateMaterialAsync(Guid experimentId, string barcodeData)
		{
			try
			{
				_logger.LogInformation($"应用服务: 开始手动验证物料，实验ID:{experimentId}，条码:{barcodeData}");

				// TODO: 实现手动验证物料的具体逻辑
				// 主要步骤：
				// - 获取实验所需物料信息
				// - 解析条码数据
				// - 比对条码数据与所需物料是否匹配
				// - 验证物料有效期、批次等信息

				// 临时返回验证成功
				return await Task.FromResult(new OperationResult { Success = true, Message = "物料验证成功" });
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 手动验证物料时发生错误，实验ID:{experimentId}，条码:{barcodeData}");
				return new OperationResult { Success = false, Message = $"物料验证失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 手动放置物料
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <param name="materialId">物料ID</param>
		/// <param name="position">位置</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ManualPlaceMaterialAsync(Guid experimentId, Guid materialId, string position)
		{
			try
			{
				_logger.LogInformation($"应用服务: 开始手动放置物料，实验ID:{experimentId}，物料ID:{materialId}，位置:{position}");

				// TODO: 实现手动放置物料的具体逻辑
				// 主要步骤：
				// - 验证物料和位置的有效性
				// - 更新实验的物料位置信息
				// - 记录操作日志

				// 临时返回操作成功
				return await Task.FromResult(new OperationResult { Success = true, Message = "物料放置成功" });
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 手动放置物料时发生错误，实验ID:{experimentId}，物料ID:{materialId}，位置:{position}");
				return new OperationResult { Success = false, Message = $"物料放置失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 从特定阶段恢复实验
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <param name="resumeStage">要恢复的阶段</param>
		/// <param name="resumeSubStage">要恢复的子阶段，为null时从阶段起始点开始</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ResumeExperimentAsync(
			Guid experimentId,
			ExperimentStage resumeStage,
			ExperimentSubStage? resumeSubStage = null)
		{
			try
			{
				_logger.LogInformation($"应用服务: 尝试从阶段 {resumeStage} {(resumeSubStage.HasValue ? $"子阶段 {resumeSubStage}" : "")} 恢复实验 {experimentId}");

				// 获取实验
				var experiment = await _experimentRepository.GetByIdAsync(experimentId);
				if (experiment == null)
				{
					_logger.LogWarning($"应用服务: 找不到实验 {experimentId}");
					return new OperationResult { Success = false, Message = $"找不到实验 {experimentId}" };
				}

				// 检查实验状态是否为失败或暂停
				if (experiment.Status != ExperimentStatus.Failed && experiment.Status != ExperimentStatus.Paused)
				{
					string message = $"只能恢复失败或暂停状态的实验，当前状态: {experiment.Status}";
					_logger.LogWarning($"应用服务: {message}");
					return new OperationResult { Success = false, Message = message };
				}

				// 更新实验状态为进行中
				experiment.Status = ExperimentStatus.Running;
				experiment.ErrorMessage = null; // 清除错误信息
				await _experimentRepository.UpdateAsync(experiment);

				// 调用领域服务恢复实验
				var result = await _experimentProcessService.ResumeExperimentAsync(experiment, resumeStage, resumeSubStage);

				if (result.Success)
				{
					// 如果恢复成功且执行到了实验结束，更新状态为完成
					if (experiment.CurrentStage == ExperimentStage.Completed)
					{
						experiment.Status = ExperimentStatus.Completed;
						experiment.ExecutionEndTime = DateTime.Now;
						await _experimentRepository.UpdateAsync(experiment);
					}

					_logger.LogInformation($"应用服务: 成功从阶段 {resumeStage} 恢复实验 {experimentId}");
				}
				else
				{
					// 恢复过程中出现错误，更新为失败状态
					await HandleExperimentFailureAsync(experiment, result.Message, $"从阶段 {resumeStage} 恢复");
				}

				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"应用服务: 从阶段 {resumeStage} 恢复实验 {experimentId} 时发生错误");

				// 获取实验并更新状态
				var experiment = await _experimentRepository.GetByIdAsync(experimentId);
				if (experiment != null)
				{
					await HandleExperimentFailureAsync(experiment, ex.Message, $"从阶段 {resumeStage} 恢复");
				}

				return new OperationResult { Success = false, Message = $"恢复实验过程中发生异常: {ex.Message}" };
			}
		}

		/// <summary>
		/// 执行设备初始化
		/// </summary>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> InitializeDevicesAsync()
		{
			try
			{
				_logger.LogInformation("应用服务: 开始执行设备初始化");

			    //用领域服务执行设备初始化
			    var result = await _experimentProcessService.InitializeDevicesAsync();

				if (result.Success)
				{
					_logger.LogInformation("应用服务: 设备初始化成功");
				}
				else
				{
					_logger.LogWarning($"应用服务: 设备初始化失败: {result.Message}");
				}
				return result;


			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "应用服务: 执行设备初始化时发生错误");
				return new OperationResult { Success = false, Message = $"设备初始化失败: {ex.Message}" };
			}
		}

		#region IDisposable实现

		/// <summary>
		/// 释放资源
		/// </summary>
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		/// <summary>
		/// 释放资源
		/// </summary>
		/// <param name="disposing">是否正在释放托管资源</param>
		protected virtual void Dispose(bool disposing)
		{
			if (!disposing)
				return;

			// 取消事件订阅
			if (_experimentProcessService != null)
			{
				_experimentProcessService.ExperimentStageChanged -= OnDomainExperimentStageChanged;
				_experimentProcessService.ExperimentSubStageChanged -= OnDomainExperimentSubStageChanged;
			}

			_logger?.LogDebug("应用服务: ExperimentProcessAppService已释放");
		}

		/// <summary>
		/// 析构函数
		/// </summary>
		~ExperimentProcessAppService()
		{
			Dispose(false);
		}

		#endregion
	}
}